using System;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Reflection;
using System.Windows.Forms;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Diagnostics;
using CSScriptLibrary;
using csscript;
using System.Resources;

class Scripting
{
    class Script
    {
        [STAThread]
        static public void Main(string[] args)
        {
            const string usage = "Usage: cscscript res <fileIn> <fileOut>...\n" +
                                "Generates .resources file.\n" +
                                "fileIn - input file (etc .bmp). Specify 'dummy' to prepare empty .resources file (etc. css res dummy Scripting.Form1.resources).\n" +
                                "fileOut - output file name (etc .resource).\n";

            try
            {
                if (args.Length < 2)
                    Console.WriteLine(usage);
                else
                {
                    Environment.CurrentDirectory = Path.GetDirectoryName(CSSEnvironment.PrimaryScriptFile);

                    //currently no .resx compilation with ResGen.exe is implemented, only dummy ressource copying
                    if (string.Compare(args[0], "dummy") == 0)
                    {
                        if (Environment.GetEnvironmentVariable(@"CSSCRIPT_DIR") == null)
                            return; //CS-Script is not installed

                        string srcFile = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\resources.template");
                        string destFile = ResolveAsmLocation(args[1]);

                        if (!File.Exists(destFile))
                            File.Copy(srcFile, destFile, true);
                    }
                    else
                    {
                        var fileToEmbedd = Environment.ExpandEnvironmentVariables(args[0]);
                        var resFile = Environment.ExpandEnvironmentVariables(args[1]);

                        if (fileToEmbedd.EndsWith(".resx", StringComparison.OrdinalIgnoreCase))
                        {
                            var inpur_resx = fileToEmbedd;
                            Run("ResGen.exe", "\"" + inpur_resx + "\" \"" + resFile + "\"", Path.GetDirectoryName(inpur_resx));
                        }
                        else
                        {
                            var destDir = Path.GetDirectoryName(resFile);

                            if (!Directory.Exists(destDir))
                                Directory.CreateDirectory(destDir);

                            using (ResourceWriter resourceWriter = new ResourceWriter(resFile))
                            {
                                resourceWriter.AddResource(Path.GetFileName(fileToEmbedd), File.ReadAllBytes(fileToEmbedd));
                                resourceWriter.Generate();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }

        static string ResolveAsmLocation(string file)
        {
            if (CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)
                return Path.Combine(CSSEnvironment.GetCacheDirectory(CSSEnvironment.PrimaryScriptFile), Path.GetFileName(file));
            else
                return Path.Combine(Path.GetDirectoryName(CSSEnvironment.PrimaryScriptFile), file);
        }

        static void Run(string file, string args, string workingDirectory)
        {
            var proc = new Process();
            proc.StartInfo.FileName = file;
            proc.StartInfo.Arguments = args;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WorkingDirectory = workingDirectory;
            proc.Start();

            string line = null;
            var firstErrorLine = true;

            while (null != (line = proc.StandardError.ReadLine()))
            {
                if (firstErrorLine)
                {
                    firstErrorLine = false;
                    Console.WriteLine("Cannot compile resources...");
                }
                Console.WriteLine(line);
            }
            proc.WaitForExit();
        }
    }
}